const router = require("koa-router")();
const jwt = require("jsonwebtoken");
const util = require("util"); // nodejs自带工具
const verify = util.promisify(jwt.verify); // 把jwt的verfy变成promis的形式,因为verfy是个callback的形式
const { SECRET } = require("../conf/constants");

router.prefix("/users");

// 模拟登陆
router.post("/login", async (ctx, next) => {
  const { userName, password } = ctx.request.body;
  let userInfo;
  if (userName === "zhangsan" && password === "abc") {
    // 登陆成功
    userInfo = {
      userId: 1,
      userName: "zhangsan",
      nickName: "张三",
      gender: 1,
    };
  }

  // 加密userInfo
  let token;
  if (userInfo) {
    token = jwt.sign(userInfo, SECRET, { expiresIn: "1h" }); // 1小时过期
  }

  if (userInfo == null) {
    ctx.body = {
      errno: -1,
      msg: "登陆失败",
    };
    return;
  }

  ctx.body = {
    errno: 0,
    data: token,
  };
});

// 获取用户信息
router.get("/getUserInfo", async (ctx, next) => {
  const token = ctx.header.authorization;
  try {
    // 去掉 Bearer多余字段
    const payload = await verify(token.split(" ")[1], SECRET);
    ctx.body = {
      error: 0,
      userInfo: payload,
    };
  } catch (ex) {
    ctx.body = {
      error: -1,
      userInfo: "verify token failed",
    };
  }
});

module.exports = router;
